import { Injectable } from '@nestjs/common';
import { Like, Repository } from 'typeorm';
import { User } from '../entities/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { MysqlBaseService } from './mysql-base.service';

@Injectable()
export class UserService extends MysqlBaseService<User> {
  constructor(
    // 一个User实体对应数据库里一张user表，也会对应一个UserRepository仓库
    @InjectRepository(User) protected repository: Repository<User>,
  ) {
    super(repository);
  }

  async findAll(keyword?: string) {
    // Like 查询，模糊查询
    const where = keyword
      ? [{ username: Like(`%${keyword}%`) }, { email: Like(`%${keyword}%`) }]
      : {};
    return this.repository.find({ where });
  }

  /**
   * 分页查询
   * @param page
   * @param limit
   * @param keyword
   */
  async findAllWithPagination(page: number, limit: number, keyword?: string) {
    // Like 查询，模糊查询
    const where = keyword
      ? [{ username: Like(`%${keyword}%`) }, { email: Like(`%${keyword}%`) }]
      : {};
    const [users, total] = await this.repository.findAndCount({
      where,
      skip: (page - 1) * limit, // 从第几条开始(跳过几条)
      take: limit, // 返回多少条
    });
    return { users, total };
  }
}
